package com.shop.dao.impl;

import com.shop.dao.UserDao;
import com.shop.entity.ShowPageT;
import com.shop.entity.User;
import com.shop.tools.JdbcTool;

import java.sql.SQLException;
import java.util.List;

/**
 * com.angluzha.shop.dao.impl文档说明
 *
 * @author Angluzha
 * @version 2022/9/13
 */
public class UserDaoImpl implements UserDao{

    @Override
    public User selectOne(User user) throws SQLException {
        String sql = "select * from s_user where id= ? or username=?";
        return JdbcTool.selectOne(User.class,sql,user.getId(),user.getUsername());
    }

    @Override
    public boolean update(User user) {
        String sql = "update s_user set username=?,email=?,sex =?,pwd=? where id=?";
        return JdbcTool.write(sql,user.getUsername(),user.getEmail(),user.getSex(),user.getPassword(),user.getId())>0;
    }

    @Override
    public boolean insert(User user) {
        String sql = "INSERT into s_user(username,email,sex,statu,pwd,uuid) values(?,?,?,?,?,?)";
        return JdbcTool.write(sql,user.getUsername(),user.getEmail(),user.getSex(),user.getStatus(),user.getPassword(),user.getUuid())>0;
    }

    @Override
    public boolean deleteById(Integer id) {
        String sql = "delete from s_user where id = ?";
        return JdbcTool.write(sql,id)>0;
    }

    @Override
    public List<User> selectAll() throws SQLException {
        String sql = "select * from s_user";
        return JdbcTool.selectList(User.class,sql);
    }

    @Override
    public ShowPageT<User> selectPage(ShowPageT<User> page) throws SQLException {
        String sql = "SELECT * FROM s_user LIMIT ?,?";
        String sql2 = "select count(1) from s_user";
        page.setCount(JdbcTool.selectResult(Integer.class,sql2));
        page.setData(JdbcTool.selectList(User.class,sql,page.getSize()*(page.getPage()-1),page.getSize()));
        return page;
    }

    @Override
    public int delCheck(List<Integer> list) {
        StringBuffer sql = new StringBuffer("delete from s_user where id in(");
        list.forEach(e->{
            sql.append("?,");
        });
        sql.deleteCharAt(sql.length()-1).append(")");
        return JdbcTool.write(String.valueOf(sql),list.toArray());
    }

    @Override
    public boolean selectByEmail(String email) throws SQLException {
        String sql ="select count(1) from s_user where email = ?";
        return JdbcTool.selectResult(Integer.class,sql,email)>0;
    }

    @Override
    public boolean exist(String code) throws SQLException {
        String sql = "select count(1) from s_user where uuid=? and statu = 0";
        return JdbcTool.selectResult(Integer.class,sql,code)>0;
    }

    @Override
    public boolean activation(String code) {
        String sql ="update s_user set statu=1 where uuid=?";
        return JdbcTool.write(sql,code)>0;
    }
}
